import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_magic_planet/common/constant.dart';
import 'package:flutter_magic_planet/model/video.dart';
import 'package:flutter_magic_planet/model/video_api_source.dart';
import 'package:flutter_magic_planet/module/video/video_player/video_player_view.dart';
import 'package:get/get.dart';

import 'video_list_logic.dart';

class VideoListPage extends StatefulWidget {
  final String? option;
  final String query;

  const VideoListPage({Key? key, this.option, required this.query})
      : super(key: key);

  @override
  _VideoListPageState createState() => _VideoListPageState();
}

class _VideoListPageState extends State<VideoListPage>
    with TickerProviderStateMixin {
  final VideoListLogic logic = Get.put(VideoListLogic());
  TabController? tabController;
  var videoApiSourceList = <VideoApiSource>[];
  var imgW;
  var imgH;
  int tabCount = -1;

  init() async {
    if (videoApiSourceList.length == tabCount) {
      return;
    }
    videoApiSourceList = await logic.fetchApiSource();
    tabController =
        TabController(length: videoApiSourceList.length, vsync: this);
    tabCount = videoApiSourceList.length;
    setState(() {});
  }

  @override
  void initState() {
    tabController =
        TabController(length: videoApiSourceList.length, vsync: this);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    init();
    logic.init(query: widget.query, option: widget.option, vsync: this);

    if (imgW == null) {
      imgW = MediaQuery.of(context).size.width / 5;
      imgH = imgW / 0.75;
    }

    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.dark,
        backgroundColor: Colors.black,
        iconTheme: IconThemeData(color: Colors.white),
        title: Text(
          widget.query,
          style: TextStyle(color: Colors.white),
        ),
        bottom: TabBar(
          controller: tabController,
          isScrollable: true,
          labelColor: Colors.white,
          indicatorColor: Colors.white,
          tabs: videoApiSourceList.map((e) {
            return new Tab(
              text: e.title,
            );
          }).toList(),
        ),
      ),
      body: Padding(
        padding: EdgeInsets.symmetric(horizontal: 14, vertical: 12),
        child: TabBarView(
          controller: tabController,
          children: videoApiSourceList.isEmpty
              ? []
              : videoApiSourceList.map((e) {
                  return ListView.builder(
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: EdgeInsets.symmetric(vertical: 8),
                        child: _buildItem(e.videos![index], e.id!),
                      );
                    },
                    itemCount: e.videos!.length,
                  );
                }).toList(),
        ),
      ),
    );
  }

  @override
  void dispose() {
    Get.delete<VideoListLogic>();
    if (tabController != null) {
      tabController!.dispose();
    }
    super.dispose();
  }

  _buildItem(Video bean, String sourceIndex) {
    var cover = bean.cover ?? emptyImage;
    cover = cover.trim().replaceAll('%20', '');
    print('[$cover]');
    return InkWell(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Card(
            child: CachedNetworkImage(
              width: imgW,
              height: imgH,
              fit: BoxFit.cover,
              imageUrl: cover,
            ),
            clipBehavior: Clip.antiAlias,
            elevation: 5.0,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(
                Radius.circular(5.0),
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.all(5.0),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  bean.videoType ?? '',
                  style: getStyle(Colors.grey, 12.0),
                ),
                Text(bean.title ?? '' + '(${bean.author})',
                    style: getStyle(Colors.black, 15.0, bold: true)),
                Text('导演: ${bean.author ?? '暂无'}',
                    style: getStyle(Colors.grey, 13.0)),
                Text(bean.descs ?? '暂无简介',
                    overflow: TextOverflow.ellipsis,
                    maxLines: 3,
                    style: getStyle(Colors.grey, 13.0)),
              ],
            ),
          )
        ],
      ),
      onTap: () {
        Get.to(
          () => VideoPlayerPage(
            video: bean,
            sourceId: sourceIndex,
          ),
        );
      },
    );
  }

  TextStyle getStyle(Color color, double fontSize, {bool bold = false}) {
    return TextStyle(
      color: color,
      fontSize: fontSize,
      fontWeight: bold ? FontWeight.bold : FontWeight.normal,
    );
  }
}
